<template>
  <div class="app-container">
    <el-card class="chat-box">
      <!-- 聊天记录区域 -->
      <div class="chat-messages" ref="messageContainer">
        <div v-for="(msg, index) in chatMessages"
             :key="index"
             :class="['message-item', msg.role]">
          <div class="avatar">
            <el-avatar :size="40" :icon="msg.role === 'user' ? 'el-icon-user' : 'el-icon-service'"></el-avatar>
          </div>
          <div class="message-content">
            <div class="message-text">{{ msg.content }}</div>
          </div>
        </div>
        <div v-if="isLoading" class="message-item assistant">
          <div class="avatar">
            <el-avatar :size="40" icon="el-icon-service"></el-avatar>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <el-input
          v-model="messageInput"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题..."
          :disabled="isLoading"
          @keyup.ctrl.enter.native="sendMessage"
        >
        </el-input>
        <div class="button-area">
          <el-button
            type="primary"
            :loading="isLoading"
            @click="sendMessage"
          >
            发送消息
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { startChatStream } from '@/api/patient/chat/chat'

export default {
  name: 'ChatInterface',
  data() {
    return {
      chatMessages: [],
      messageInput: '',
      isLoading: false,
      userId: 'user_' + Date.now()
    }
  },
  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageContainer
        container.scrollTop = container.scrollHeight
      })
    },
    async sendMessage() {
      if (!this.messageInput.trim() || this.isLoading) {
        return
      }

      // 添加用户消息
      this.chatMessages.push({
        role: 'user',
        content: this.messageInput
      })

      const message = this.messageInput
      this.messageInput = ''
      this.scrollToBottom()
      this.isLoading = true

      try {
        // 准备请求参数
        const params = {
          userId: this.userId,
          message: message
        }

        // 创建 EventSource 连接
        const eventSource = new EventSource(
          `/dev-api/inquiry/chat/stream?${new URLSearchParams(params).toString()}`
        )

        // 创建助手消息
        const assistantMessage = {
          role: 'assistant',
          content: ''
        }
        this.chatMessages.push(assistantMessage)

        // 调用API
        await startChatStream(params)

        eventSource.onmessage = (event) => {
          if (event.data === '[DONE  ]') {
            eventSource.close()
            this.isLoading = false
          } else {
            assistantMessage.content += event.data
            this.scrollToBottom()
          }
        }

        eventSource.onerror = (error) => {
          console.error('EventSource failed:', error)
          this.$modal.msgError('连接出错，请重试')
          eventSource.close()
          this.isLoading = false
        }
      } catch (error) {
        console.error('Error:', error)
        this.$modal.msgError('发送消息失败')
        this.isLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-box {
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;

  ::v-deep .el-card__body {
    height: 100%;
    padding: 0;
    display: flex;
    flex-direction: column;
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f5f5;
}

.message-item {
  display: flex;
  margin-bottom: 20px;

  &.user {
    flex-direction: row-reverse;

    .message-content {
      margin-right: 10px;
      margin-left: 60px;

      .message-text {
        background: #409EFF;
        color: white;
        border-radius: 10px 2px 10px 10px;
      }
    }
  }

  &.assistant {
    .message-content {
      margin-left: 10px;
      margin-right: 60px;

      .message-text {
        background: white;
        border-radius: 2px 10px 10px 10px;
      }
    }
  }
}

.message-content {
  flex: 1;

  .message-text {
    padding: 12px 16px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    word-break: break-word;
    line-height: 1.5;
  }
}

.chat-input {
  padding: 20px;
  background: white;
  border-top: 1px solid #EBEEF5;

  .button-area {
    margin-top: 10px;
    text-align: right;
  }
}

// 打字指示器动画
.typing-indicator {
  background-color: #f0f0f0;
  padding: 12px 16px;
  border-radius: 10px;
  display: flex;
  gap: 4px;

  span {
    width: 8px;
    height: 8px;
    background: #90949c;
    border-radius: 50%;
    animation: bounce 1.3s linear infinite;

    &:nth-child(2) {
      animation-delay: 0.15s;
    }

    &:nth-child(3) {
      animation-delay: 0.3s;
    }
  }
}

@keyframes bounce {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-4px);
  }
}
</style>
